package com.pie.face_pie.service;

import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.MatOfRect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;
import java.io.IOException;

@Component
public class DetectService {
    public int detect(MultipartFile file) throws IOException {

        //将图片转换为Mat
        byte[] bytes = file.getBytes();
        Mat mat = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.IMREAD_UNCHANGED);
        Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2GRAY);
        Imgproc.GaussianBlur(mat, mat, new org.opencv.core.Size(3, 3), 0, 0);
        //加载人脸识别模型
        CascadeClassifier cascadeClassifier = new CascadeClassifier(".\\face_pie\\src\\main\\resources\\xml\\haarcascade_frontalface_default.xml");
        //检测人脸
        MatOfRect matOfRect = new MatOfRect();
        cascadeClassifier.detectMultiScale(mat, matOfRect);
        //如果检测到一张人脸，则裁剪出人脸并保存到本地；如果检测到多张，那么直接返回0
        // System.out.println(matOfRect.toArray().length);
        if (matOfRect.toArray().length == 1) {
            // Mat face = mat.submat(matOfRect.toArray()[0]);
            // Imgcodecs.imwrite(".\\detect_picture\\" + id + "\\" + count, face);
            return 1;
        }
        return 0;   //返回0表示未检测到人脸或检测到多张
    }
}
